/*
 * PhotonCounter.h
 *
 *  Created on: Oct 5, 2010
 *      Author: blyth
 */

#ifndef PHOTONCOUNTER_H_
#define PHOTONCOUNTER_H_

int** Veto(int,int,int**,int&);
bool IsVetod(int,int,int**,int);

int PhotonCounter(TH2D* h){
	int photons = 0;

	int vetoCount = 0;
	int** vetoList = new int*[vetoCount];

	bool centerFlag = false;

	for(int i = 0;i < 72;i++){
		for(int j = 0;j < 72;j++){
			if(h->GetBinContent(i+1,j+1) > 20*MeV && !IsVetod(i,j,vetoList,vetoCount)){
				vetoList = Veto(i,j,vetoList,vetoCount);

				int newVetos = 1;
				while(newVetos > 0){
					for(int di = -2;di < 3;di++){
						for(int dj = -2;dj < 3;dj++){
							int testI = vetoList[vetoCount-newVetos][0]+di;
							int testJ = vetoList[vetoCount-newVetos][1]+dj;
							if(testI < 0 || testI > 71 || testJ < 0 || testJ > 71) continue;

							double testContent = h->GetBinContent(testI+1,testJ+1);
							if(testContent > 0 && !IsVetod(testI,testJ,vetoList,vetoCount)){
								vetoList = Veto(testI,testJ,vetoList,vetoCount);
								newVetos++;
							}
							else if(testI > 31 && testI < 40 && testJ > 31 && testJ < 40 && !centerFlag){
								for(int n = 32;n < 40;n++){
									vetoList = Veto(n,32,vetoList,vetoCount);
									vetoList = Veto(n,39,vetoList,vetoCount);
									if(n > 32 && n < 39){
										vetoList = Veto(32,n,vetoList,vetoCount);
										vetoList = Veto(39,n,vetoList,vetoCount);
									}
								}
								centerFlag = true;
							}
						}
					}

					newVetos--;
				}

				photons++;
			}
		}
	}

	for(int i = 0;i < vetoCount;i++){
		delete vetoList[i];
	}
	delete vetoList;

	std::cout << photons << "\n";

	return photons;
}

int** Veto(int i,int j,int** vetoList,int& vetoCount){
	vetoCount++;
	int** newVetoList = new int*[vetoCount];

	for(int l = 0;l < vetoCount-1;l++){
		newVetoList[l] = vetoList[l];
	}
	delete vetoList;

	newVetoList[vetoCount-1] = new int[2];
	newVetoList[vetoCount-1][0] = i;
	newVetoList[vetoCount-1][1] = j;

	return newVetoList;
}

bool IsVetod(int i,int j,int** vetoList,int vetoCount){
	for(int l = 0;l < vetoCount;l++){
		if(vetoList[l][0] == i && vetoList[l][1] == j) return true;
	}

	return false;
}

#endif /* PHOTONCOUNTER_H_ */
